#!flask/bin/python
import os
import unittest
import datetime

from flask.ext.testing import LiveServerTestCase

from config import LOG_DIR
from golsee import db ,golsee
from golsee.models import User, Blog_info

class MyTestCase(unittest.TestCase):
    def setUp(self):
        golsee.config['CSRF_ENABLED'] = False
        golsee.config['TESTING'] = True
        golsee.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(LOG_DIR, 'test.db')
        self.app = golsee.test_client()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()


class MyLiveServerTestCase(LiveServerTestCase):
    def create_app(self):
        golsee.config['CSRF_ENABLED'] = False
        golsee.config['TESTING'] = True
        golsee.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(LOG_DIR, 'test.db')
        return golsee.test_client()


class TestUser(MyTestCase):
    def test_avatar(self):
        u = User(nicename='john', email='john@example.com')
        avatar = u.avatar(128)
        expected = 'http://www.gravatar.com/avatar/d4c74594d841139328695756648b6bd6'
        assert avatar[0:len(expected)] == expected

    def test_user_check(self):
        pwd = User.make_random_passwd(email='abc@qq.com')
        user = User(email=pwd['email'],
                    passwd=pwd['pwdmd5'],
                    salt=pwd['salt'])
        db.session.add(user)
        db.session.commit()
        is_true = User.user_check('abc@qq.com', pwd['pwd'])
        assert is_true is not False


class TestBlogInfo(MyTestCase):
    date = str(datetime.datetime.now().date())

    def test_get_info_by_day(self):
        old = Blog_info.get_info_by_day(self.date)
        assert old is not None

    def test_new_visit(self):
        old = Blog_info.get_info_by_day(self.date)
        old_visit_day = old.visit_day
        old_visit_all = old.visit_all
        Blog_info.new_visit(self.date)
        new = Blog_info.get_info_by_day(self.date)
        new_visit_day = new.visit_day
        new_visit_all = new.visit_all
        assert old_visit_day + 1 == new_visit_day and old_visit_all + 1 == new_visit_all

class TestViews(unittest.TestCase):
    def test_some_json(self):
        response = self.client.get("/calendar_json/")
        self.assertEquals(response.json, dict(success=True))

class TestJson(MyLiveServerTestCase):
    def test_server_is_up_and_running(self):
        import urllib2
        response = urllib2.urlopen(self.get_server_url())
        self.assertEqual(response.code, 200)

    def test_calendar_json(self):
        response = self.client.get("/calendar_json")
        self.assertEquals(response.json, dict(success=True))


if __name__ == '__main__':
    unittest.main()